local addon = LibStub("AceAddon-3.0"):GetAddon("Poppins")

local count = 0
local weak = {__mode='k'}
local cache = setmetatable({}, weak)
local used = setmetatable({}, weak)

local prototype = addon:CreateClass("Frame")
addon.Header = prototype

function prototype:Create()
	local button = next(cache)
	if button then
		cache[button] = nil
	else
		count = count + 1
		local name = format("%sHeader%d", addon.name, count)
		button = self:Bind(CreateFrame("Frame", name, UIParent, "SecureHandlerStateTemplate"))
		button.rid = count

		button:SetAttribute("_onstate-active", [[ -- self, stateid, newstate
			if state == newstate then return end
			state = newstate

			local active = self:GetFrameRef(newstate)
			active:SetAlpha(0.5)
			active:SetScale(1)
			active:ClearAllPoints()
			active:SetPoint("CENTER", self, "CENTER")

			local diff = ((((36 + padding) / scale2) + ((36 + padding) * scale)) / 2)
			local buttons = self:GetChildList(table.new())
			for i, button in ipairs(buttons) do
				if button ~= active then
					button:SetAlpha(0.5)
					button:SetScale(1)
					local id = button:GetID() - 1
					if swap and id >= active:GetID() then
						id = id - 1
					end
					local offset = diff + ((36 + padding) * id)
					button:ClearAllPoints()
					button:SetPoint("CENTER", self, "CENTER", offset * x, offset * y)
				end
			end
			table.wipe(buttons)
		]])
		button:SetAttribute("_onstate-hover", [[ -- self, stateid, newstate
			control:SetAnimating(newstate)
			self:SetAttribute("state-alpha", newstate)

			local active = self:GetFrameRef(self:GetAttribute("state-active"))
			local buttons = self:GetChildList(table.new())
			for i, button in ipairs(buttons) do
				if button ~= active then
					if newstate then
						button:Show()
					else
						button:Hide()
					end
				end
			end
			table.wipe(buttons)
		]])
		button:SetAttribute("_onstate-alpha", [[ -- self, stateid, newstate
			local active = self:GetFrameRef(self:GetAttribute("state-active"))
			if newstate then
				active:SetAlpha(1)
			else
				active:SetAlpha(0.5)
			end

			local buttons = self:GetChildList(table.new())
			for i, button in ipairs(buttons) do
				if button ~= active then
					if newstate then
						button:SetAlpha(1)
					else
						button:SetAlpha(0.5)
					end
				end
			end
			table.wipe(buttons)
		]])
		button:SetAttribute("_onupdate", [[
			if not timer or self:IsUnderMouse(true) then
				timer = 0.5
			else
				if timer == 0.5 then
					self:SetAttribute("state-alpha", false)
				end
				timer = timer - elapsed
			end
			if timer > 0 then return end
			timer = nil
			self:SetAttribute("state-hover", false)
		]])

		button.popups = {}
	end
	used[button] = true

	return button
end

function addon:IterateHeader()
	return pairs(used)
end

function prototype:Store()
	used[self] = nil

	local popups = self.popups
	for i=(#popups + 1), 1, -1 do
		popups[i - 1]:Store()
	end

	self:ClearAllPoints()
	self:Hide()
	
	cache[self] = true
end